package com.celesea.auth.role.service;

import com.celesea.auth.role.dao.RoleUserDao;
import com.celesea.auth.role.entity.Role;
import com.celesea.auth.role.entity.RoleUser;
import com.celesea.auth.role.vo.RoleVo;
import com.celesea.framework.service.AbstractBaseService;
import com.celesea.framework.util.CollectionKit;
import com.celesea.framework.util.EnvUtil;
import com.celesea.framework.vo.DictionaryVo;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author JackYuan
 * @create 2017-10-28 20:48
 */
@Service
public class RoleUserServiceImpl extends AbstractBaseService<RoleUser> implements RoleUserService {

    public static final String ROLE_ID = "roleId";
    @Autowired
    private RoleUserDao roleUserDao;

    @Override
    public List<RoleUser> findByRole(String roleId) {
        return roleUserDao.selectByExample(buildExample(roleId));
    }

    @Override
    public int deleteByRole(String roleId) {
        return roleUserDao.deleteByExample(buildExample(roleId));
    }

    @Override
    public int insertByRole(RoleVo entity) {
        List<RoleUser> roleUsers = Lists.newArrayList();
        if (CollectionKit.isNotEmpty(entity.getUsers())) {
            roleUsers = entity.getUsers().stream().map(
                    item -> generatPk(new RoleUser(entity, item))
            ).collect(Collectors.toList());
        }
        if (CollectionKit.isNotEmpty(roleUsers)) {
            return roleUserDao.insertList(roleUsers);
        }
        return 0;
    }

    @Override
    public List<DictionaryVo> findByRoleCode(String code) {
        Role role=new Role();
        role.setCode(code);
        role.setTenantId(EnvUtil.getTenantId());
        return roleUserDao.findByRoleCode(role);
    }

    private Example buildExample(String roleId) {
        Example example = new Example(RoleUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(ROLE_ID, roleId);
        return example;
    }


}
